// 外网国密
import smCrypto from 'sm-crypto'

export default {

  /** ****************** 外网国密 ******************** */

  /**
   * 外网SM2生成密钥
   * @returns {object} keypair
   * keypair.privateKey 私钥
   * keypair.publicKey  公钥
   */
  genKeysSM2() {
    const sm2 = smCrypto.sm2
    const keypair = sm2.generateKeyPairHex()
    return keypair
  },

  /**
   * 外网SM2加密
   * @param {String} plaintext
   * @param {String} publicKey 十六位
   */
  encryptSM2(plaintext, publicKey) {
    console.log('SM2加密 文本大小：', (plaintext.length / 1024 + 'kb'))
    console.time('encryptSM2External')
    const sm2 = smCrypto.sm2
    const ciphertext = sm2.doEncrypt(plaintext, publicKey, 1)
    return '04' + ciphertext
  },

  /**
 * 外网SM2解密
 * @param {String} ciphertext
 * @param {String} privateKey
 */
  decryptSM2(ciphertext, privateKey) {
    console.log('SM2解密 文本大小：', (ciphertext.length / 1024 + 'kb'))
    console.time('decryptSM2')
    const sm2 = smCrypto.sm2
    const plaintext = sm2.doDecrypt(ciphertext.toUpperCase(), privateKey)
    console.timeEnd('decryptSM2')
    return plaintext
  },

  /**
   * 外网SM3
   * @param {String} text
   */
  encryptSM3(text) {
    console.log('SM3加密 文本大小：', (text.length / 1024 + 'kb'))
    console.time('encryptSM3')
    const sm3 = smCrypto.sm3
    const abc = sm3(text).toUpperCase()
    console.timeEnd('encryptSM3')
    return abc
  },

  /**
   * 外网SM4生成密钥
   * @returns String key
   * keypair.privateKey 私钥
   */
  genKeysSM4() {
    let result = ''
    for (let i = 0; i < 32; i++) {
      result += Math.floor(Math.random() * 16).toString(16)
    }
    return result.toUpperCase()
  },

  /**
   * 外网SM4加密
   * @param {String} plaintext
   * @param {String} key
   */
  encryptSM4(plaintext, key) {
    console.log('SM4加密 文本大小：', (plaintext.length / 1024 + 'kb'))
    console.time('encryptSM4')
    const sm4 = smCrypto.sm4
    const ciphertext = sm4.encrypt(plaintext, key, { padding: 'pkcs#5' })
    console.timeEnd('encryptSM4')
    return ciphertext
  },

  /**
   * 外网SM4解密
   * @param {String} ciphertext
   * @param {String} key
   */
  decryptSM4(ciphertext, key) {
    console.log('SM4解密 文本大小：', (ciphertext.length / 1024 + 'kb'))
    console.time('decryptSM4')
    const sm4 = smCrypto.sm4
    const plaintext = sm4.decrypt(ciphertext, key, { padding: 'pkcs#5' })
    console.timeEnd('decryptSM4')
    return plaintext
  }
}
